package com.qiwenshare.file.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiwenshare.common.exception.QiwenException;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.domain.Archive;
import com.qiwenshare.file.domain.Department;
import com.qiwenshare.file.domain.user.UserBean;
import com.qiwenshare.file.mapper.ArchiveMapper;
import com.qiwenshare.file.mapper.DepartmentMapper;
import com.qiwenshare.file.api.IDepartmentService;
import com.qiwenshare.file.mapper.UserMapper;
import com.qiwenshare.file.office.entities.User;
import com.qiwenshare.file.util.SpringBeanUtil;
import com.qiwenshare.file.vo.department.DepartmentTreeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.qiwenshare.file.component.InitData;

/**
 * 部门表(Department)表服务实现类
 *
 * @author makejava
 * @since 2023-09-16 19:52:33
 */
@Service("departmentService")
public class DepartmentService implements IDepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ArchiveMapper archiveMapper;


    @Override
    public List<DepartmentTreeVo> selectDepartmentTree(String departmentName) {
        List<Department> departmentList = departmentMapper.selectList(StringUtils.isBlank(departmentName) ? new QueryWrapper<>(Department.builder().build()) : new QueryWrapper<>(Department.builder()
                .build()).lambda().like(Department::getDepartmentName, departmentName));
        List<DepartmentTreeVo> treeList = new ArrayList<>();
        Map<String, String> userStaffMap = InitData.getUserStaffMap();
        for (Department department : departmentList) {
            if (StringUtils.isBlank(department.getParentDepartmentId())) {
                DepartmentTreeVo treeVo = SpringBeanUtil.copyProperties(department, DepartmentTreeVo.class);
                treeVo.setTitle(treeVo.getDepartmentName());
                treeVo.setValue(treeVo.getDepartmentId());
                treeVo.setCreateUser(InitData.getStaffNameByUserId(treeVo.getCreateUserId()));
                treeVo.setModifyUser(InitData.getStaffNameByUserId(treeVo.getModifyUserId()));
                treeList.add(treeVo);
            }
        }
        generateTree(departmentList, treeList, userStaffMap);
        return treeList;
    }

    @Override
    public List<Department> getList() {
        return departmentMapper.selectList(new QueryWrapper<>(Department.builder().build()));
    }

    private void generateTree(List<Department> departmentList, List<DepartmentTreeVo> treeList, Map<String, String> userStaffMap) {
        for (DepartmentTreeVo treeVo : treeList) {
            List<DepartmentTreeVo> children = new ArrayList<>();
            for (Department department : departmentList) {
                if (treeVo.getDepartmentId().equals(department.getParentDepartmentId())) {
                    DepartmentTreeVo dVo = SpringBeanUtil.copyProperties(department, DepartmentTreeVo.class);
                    dVo.setTitle(department.getDepartmentName());
                    dVo.setValue(department.getDepartmentId());
                    dVo.setCreateUser(InitData.getStaffNameByUserId(department.getCreateUserId()));
                    dVo.setModifyUser(InitData.getStaffNameByUserId(department.getModifyUserId()));
                    children.add(dVo);
                }
            }
            treeVo.setChildren(children);
            if (CollectionUtil.isNotEmpty(children)) {
                generateTree(departmentList, treeVo.getChildren(), userStaffMap);
            }

        }
    }

    /**
     * 通过ID查询单条数据
     *
     * @param departmentId 主键
     * @return 实例对象
     */
    @Override
    public Department queryById(String departmentId) {
        return this.departmentMapper.queryById(departmentId);
    }

    /**
     * 分页查询
     *
     * @param department  筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<Department> queryByPage(Department department, PageRequest pageRequest) {
        long total = this.departmentMapper.count(department);
        return new PageImpl<>(this.departmentMapper.queryAllByLimit(department, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param department 实例对象
     * @return 实例对象
     */
    @Override
    public RestResult insert(Department department) {
        department.setCreateTime(DateUtil.getCurrentTime());
        department.setCreateUserId(SessionUtil.getSession().getUserId());
        department.setDepartmentId(IdUtil.getSnowflakeNextIdStr());
        RestResult result = this.departmentMapper.insert(department) > 0 ? RestResult.success() : RestResult.fail();
        return result;
    }

    /**
     * 修改数据
     *
     * @param department 实例对象
     * @return 实例对象
     */
    @Override
    public RestResult update(Department department) {
        department.setModifyTime(DateUtil.getCurrentTime());
        department.setModifyUserId(SessionUtil.getSession().getUserId());
        RestResult result = this.departmentMapper.update(department) > 0 ? RestResult.success() : RestResult.fail();
        return result;
    }

    /**
     * 通过主键删除数据
     *
     * @param departmentId 主键
     * @return 是否成功
     */
    @Override
    public RestResult deleteById(String departmentId) {
        List<Department> childrenDepartment = departmentMapper.selectList(new QueryWrapper<>(Department.builder()
                .parentDepartmentId(departmentId)
                .build()));
        if (CollectionUtil.isNotEmpty(childrenDepartment)) {
            throw new QiwenException("该归属部门下有子部门，不支持删除。");
        }

        List<Archive> archiveList = archiveMapper.selectList(new QueryWrapper<>(Archive.builder()
                .departmentId(departmentId)
                .build()));
        if (CollectionUtil.isNotEmpty(archiveList)) {
            throw new QiwenException("该归属部门已绑定档案，不支持删除。");
        }
        List<UserBean> userList = userMapper.selectList(new QueryWrapper<>(UserBean.builder()
                .departmentId(departmentId)
                .build()));
        if (CollectionUtil.isNotEmpty(userList)) {
            throw new QiwenException("该归属部门已绑定用户，不支持删除。");
        }
        RestResult result =  this.departmentMapper.deleteById(departmentId) > 0 ? RestResult.success() : RestResult.fail();

        return result;
    }
}
